package com.async.config;

import cn.hutool.core.map.MapUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 * @author yang
 * @date 2024/5/17
 */
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class SpringBeanConfig implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanConfig.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clazz) throws BeansException{
        return applicationContext.getBean(name,clazz);
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException{
        return applicationContext.getBean(clazz);
    }
    public static Object getBean(String name) throws BeansException{
        return applicationContext.getBean(name);
    }

    /**
     * 获取指定类型的全部bean
     * @param clazz bean类型
     * @param <T> bean类型泛型
     * @return map<beanName,beanType>
     */
    public static <T> Map<String,T> getBeansOfType(Class<T> clazz) throws BeansException{
        Map<String, T> beanMap = applicationContext.getBeansOfType(clazz);

        if (MapUtil.isEmpty(beanMap)){
            return Collections.emptyMap();
        }
        return beanMap;
    }
}
